package cn.xuqiudong.rpc.serializer.jdk;

import cn.xuqiudong.rpc.cluster.exception.XqdCommonException;
import cn.xuqiudong.rpc.serializer.XqdSerializer;

import java.io.*;

/**
 * 描述: 通过jdk对象流方式序列化数据
 * @author Vic.xu
 * @date 2022-02-21 11:07
 */
public class JdkSerializer implements XqdSerializer {

    @Override
    public <T> byte[] serialize(T obj) throws IOException {
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);){
            oos.writeObject(obj);
            //对象转成字节数组
            byte[] bytes = bos.toByteArray();
            return bytes;
        }catch (Exception e) {
            throw  new XqdCommonException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws IOException {
        try(ByteArrayInputStream bis = new ByteArrayInputStream(data);
        ObjectInputStream ois = new ObjectInputStream(bis);){
        return (T) ois.readObject();
        }catch (Exception e) {
            throw  new XqdCommonException(e);
        }

    }

    @Override
    public boolean selfDescribed() {
        return true;
    }
}
